//
//  JEHSearchViewController.m
//  SinaNews
//
//  Created by 蒋恩浩 on 15/12/16.
//  Copyright © 2015年 JEH. All rights reserved.
//

#import "JEHSearchViewController.h"

@interface JEHSearchViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *dataSource;
@property (nonatomic, retain) UISearchBar *searchBar;
@property (nonatomic, retain) UILabel *promptLabel;
@property (nonatomic, retain) NSTimer *timer;
@property (nonatomic, retain) UIImageView *imageBG;

@end

@implementation JEHSearchViewController

- (void)dealloc {
    
    [_dataSource release];
    [_searchBar release];
    [_tableView release];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.view nightMode];
    [self.tableView reloadData];
    [self.imageBG nightMode];
    [_promptLabel nightMode];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createSearchBar];
    [self createView];
}

- (void)createView {
    
    self.promptLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, self.view.width - 40, 50)];
    [_promptLabel release];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.4 target:self selector:@selector(changeText) userInfo:nil repeats:YES];
    self.imageBG = [[UIImageView alloc] initWithFrame:CGRectMake(10, 70, self.view.width - 20, self.view.height - 50 - 49)];
    [_imageBG release];
    self.imageBG.image = [UIImage imageNamed:@"newsBGI.jpg"];
    [self.view insertSubview:_imageBG atIndex:0];
}

static int i = 0;
#pragma mark - promptLabel
- (void)changeText {
    
    NSString *string = @" 请输入你想要的...";
    _promptLabel.font = [UIFont boldSystemFontOfSize:(self.view.width - 20) / 9];
    [self.view insertSubview:_promptLabel atIndex:1];

    NSString *newString = [string substringToIndex:i + 1];
    _promptLabel.text = newString;
    i++;
    if (i == string.length) {
        
        i = 0;
    }
}

#pragma mark - createSearchBar
- (void)createSearchBar {
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(10, 20, self.view.width - 20, 50)];
    [_searchBar release];
    _searchBar.barStyle = UIBarStyleDefault;
    _searchBar.placeholder = @"请输入关键字";
    _searchBar.delegate = self;
    _searchBar.showsCancelButton = YES;
    [self.view addSubview:_searchBar];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(10, 70, self.view.width - 20, self.view.height - 70) style:UITableViewStyleGrouped];
    _tableView.bounces = NO;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewIdentifier"];
    [self.view addSubview:self.tableView];
}

#pragma mark - tapAction
- (void)cancelFirstResponder:(UITapGestureRecognizer *)tap {
    
    [self.searchBar resignFirstResponder];
}

#pragma mark - searchBarMethod
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    
    if (searchText.length > 0) {
        
        UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        indicator.center = self.view.center;
        indicator.color = [UIColor magentaColor];
        [indicator startAnimating];
        [self.view addSubview:indicator];
        
        NSString *url = [kSearchGETURL stringByReplacingOccurrencesOfString:@"keyword=" withString:[NSString stringWithFormat:@"keyword=%@", [searchText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
        self.dataSource = [NSMutableArray arrayWithCapacity:0];
        [JEHNetWorkTool getWithUrl:url parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
            
            if (result) {
                
                NSDictionary *dictionary = result[@"data"];
                NSArray *array = dictionary[@"result"];
                if (array.count > 0) {
                    
                    for (NSDictionary *dictionary in array) {
                        
                        JEHSearchModel *search = [[JEHSearchModel alloc] initWithDictionary:dictionary];
                        [self.dataSource addObject:search];
                        [search release];
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        [self.tableView reloadData];
                        [indicator stopAnimating];
                    });
                } else {
                    [indicator stopAnimating];
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"没有搜到相关" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
                    [alert show];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        [alert dismissWithClickedButtonIndex:0 animated:NO];
                    });
                    [alert release];
                }
            }
        } fail:^(NSError *error) {
            
            [indicator stopAnimating];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请检查网络" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
            [alert show];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [alert dismissWithClickedButtonIndex:0 animated:NO];
            });
            [alert release];
        }];
    } else {
        self.dataSource = nil;
        [self.tableView reloadData];
    }
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    
    [self.searchBar resignFirstResponder];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self.searchBar resignFirstResponder];
}

#pragma mark - UITableViewMethod
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (_dataSource) {
        
        return self.dataSource.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewIdentifier"];
    if (_dataSource) {
        
        JEHSearchModel *search = self.dataSource[indexPath.row];
        cell.textLabel.text = search.text;
        [cell.textLabel searchLabel:cell.textLabel withAttributedText:self.searchBar.text];
        [cell nightMode];
        return cell;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    JEHSearchModel *search = self.dataSource[indexPath.row];
    self.searchBar.text = search.text;
    [self.searchBar resignFirstResponder];
    
    UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    indicator.center = self.view.center;
    indicator.color = [UIColor magentaColor];
    [indicator startAnimating];
    [self.view addSubview:indicator];
    NSString *url = [kSearchClickGETURL stringByReplacingOccurrencesOfString:@"keyword=" withString:[NSString stringWithFormat:@"keyword=%@", [self.searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    [JEHNetWorkTool getWithUrl:url parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        
        if (result) {

            NSDictionary *dictionary = result[@"data"];
            NSArray *array = dictionary[@"weibo"];
            if (array.count > 0) {
                
                JEHSearchModel *search = nil;
                for (NSDictionary *dictionary in array) {
                    
                    search = [[JEHSearchModel alloc] initWithDictionary:dictionary];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    JEHSearchWebViewController *searchWeb = [[JEHSearchWebViewController alloc] init];
                    searchWeb.searchModel = search;
                    [self presentViewController:searchWeb animated:YES completion:^{
                        
                    }];
                    [searchWeb release];
                    [indicator stopAnimating];
                });
            } else {
                [indicator stopAnimating];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"没有搜到相关" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
                [alert show];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [alert dismissWithClickedButtonIndex:0 animated:NO];
                });
                [alert release];
            }
        }
    } fail:^(NSError *error) {
        
        [indicator stopAnimating];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请检查网络" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [alert show];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [alert dismissWithClickedButtonIndex:0 animated:NO];
        });
        [alert release];
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 50;
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.searchBar resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
